"use strict"

/**
 * admin controller 
 * 
 */

var q = require("q");
var db = require("../db");
var dateFormat = require('dateformat');


var adminHandler = {
    addMail: function (req, res, next) {
        var ky = req.body.keywords || "";
        var eml = req.body.emails || "";
        var tip = req.body.tip || "";
        var sql = "insert into mails (tip, keywords, emails) values ('" + tip + "', '" + ky + "', '" + eml + "')";
        db.query(sql, function (err, recs) {
            res.redirect("./admin");
        });
    },
    updateMail: function (req, res) {
        var ky = req.body.keywords || "";
        var eml = req.body.emails || "";
        var id = req.body.id || "";
        var tip = req.body.tip || "";
        if (id != "") {
            var sql = "update mails set keywords='" + ky + "', emails='" + eml + "', tip='" + tip + "' where id=" + id;
            db.query(sql, function (err, recs) {
                res.redirect("./admin");
            });
        } else {
            res.redirect("./admin");
        }
    },
    index: function (req, res, next) {
        var sql = "select * from mails order by id asc";
        var defer = q("");
        defer.then(function () {
            var d = q.defer();
            db.query(sql, function (err, recs) {
                if (err) {
                    recs = [];
                }
                var renderObj = {
                    items: recs
                };
                d.resolve(renderObj);
            });
            return d.promise;
        }).then(function (renderObject) {
            res.render("admin", renderObject);
        });
    },
    delMail: function (req, res) {
        var id = req.body.id || "";
        if (id != "") {
            var sql = "delete from mails where id=" + id;
            db.query(sql, function (err, recs) {
                res.redirect("./admin");
            });
        }
    },
    editMail: function (req, res) {
        var id = req.body.id || "";
        if (id == "") {
            res.redirect("/admin");
        } else {
            var sql = "select * from mails where id=" + id + " limit 1";
            var defer = q("");
            defer.then(function () {
                var d = q.defer();
                db.query(sql, function (err, recs) {
                    d.resolve({ curr: recs[0] });
                });
                return d.promise;
            }).then(function (renderObject) {
                res.render("admin", renderObject);
            });
        }
    }
};

exports = module.exports = {
    needAuth: true, // 需要登录验证的特殊选项
    "/admin": adminHandler.index, // url maps
    "/addMail": { post: adminHandler.addMail },
    "/delMail": { post: adminHandler.delMail },
    "/editMail": { post: adminHandler.editMail },
    "/updateMail": { post: adminHandler.updateMail }
};